package cn.tedu.tweibo.controller;

import cn.tedu.tweibo.mapper.UserMapper;
import cn.tedu.tweibo.pojo.dto.UserLoginDTO;
import cn.tedu.tweibo.pojo.dto.UserRegDTO;
import cn.tedu.tweibo.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDTO user){
        UserVO u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            return 2;//代表用户名已存在
        }
        mapper.insert(user);
        return 1;//注册成功!
    }

    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO user, HttpSession session){
        UserVO u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                //登录成功时把当前登录成功的用户对象u保存到会话对象里面
                session.setAttribute("user",u);
                return 1;//登录成功
            }
            return 3;//密码错误
        }
        return 2;//用户名不存在
    }
    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        //从会话对象中得到登录成功时保存的用户对象
        return (UserVO) session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //删除登录成功时保存的用户对象
        session.removeAttribute("user");
    }

}
